/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 */

/*
 * @Author: netxeyess 2129881769@qq.com
 * @Date: 2022-08-28 00:20:37
 * @LastEditors: netxeyess 2129881769@qq.com
 * @LastEditTime: 2022-08-28 00:23:32
 * @FilePath: \undefinedc:\Users\netXeye\Desktop\袁睿 储物精灵\袁睿 储物精灵\dev\NFC entry function(In beta, the full source code cannot be committed yet)\src.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "light_demo.h"

#define ENV_LIGHT_LEVEL_LOW     1000 //低环境光AD值，模拟黄昏
#define ENV_LIGHT_LEVEL_LOWEST  1500 //超低环境光AD值，模拟黑夜

int LightSensorVal(unsigned short* val)
{
    int ret = IoTAdcRead(IOT_ADC_CHANNEL_6,val, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 256);
    if(ret != IOT_SUCCESS)
    {
        printf("Failed! Err code = %d\n", ret);
    }  
    return ret;    
}

int GetLightAverageVal(unsigned char cnt)
{
    unsigned short readVal = 0;
    unsigned int totalVal = 0, totalCnt = 0;

    for(unsigned char i=0; i<cnt; i++)
    {
        if(LightSensorVal(&readVal) == IOT_SUCCESS)
        {
            totalVal += readVal;
            totalCnt++;
        }
        usleep(50000);
    }

    return (totalVal/totalCnt); 
}

enum ENV_LIGHT_STATE GetEnvLightState(void)
{
    enum ENV_LIGHT_STATE lightState = LIGHT_DAY;

    //获取当前环境光照平均值
    int lightVal = GetLightAverageVal(5);

    //当前为黑夜环境
    if(lightVal > ENV_LIGHT_LEVEL_LOWEST)
    {
        lightState = LIGHT_NIGHT;
    }

    //当前为黄昏环境
    else if(lightVal > ENV_LIGHT_LEVEL_LOW)
    {
        lightState = LIGHT_DUSK;
    } 

    //当前为白天环境
    else
    {
        lightState = LIGHT_DAY;
    } 

    return  lightState;
}
